package com.qiantu.phone.ui.dialog;

import static android.app.Activity.RESULT_OK;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.base.BaseActivity;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.UniversalDeviceData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.SelectDeviceActivity;
import com.qiantu.phone.ui.shotview.ActChangeListener;
import com.qiantu.phone.ui.shotview.BaseDeviceActView;
import com.qiantu.phone.ui.shotview.DeviceShotActBean;
import com.qiantu.phone.ui.shotview.ShotViewManager;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.utils.DataHolder;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.util.XPopupUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.qiantu.phone.ui.uiutil.LLDeviceUtil.POWER;

public class BottomDeviceDialog extends BottomPopupView implements ActChangeListener {
    private ImageView deviceImage;
    private TextView deviceName;
    private LinearLayout VsetDeviceActs;
    private FrameLayout deviceContentLy;
    private RecyclerView actList;
    private TextView cancel;
    private TextView save;
    private TextView floorRoomName;
    private DeviceBean mDevice;
    private LinkedHashMap<String, DeviceShotActBean> mActMap = new LinkedHashMap<>();
    private boolean isOnCreate;
    private boolean isEdit;
    private BaseDeviceActView deviceView;
    private View outSide;
    private ActAdapter actAdapter;
    List<DeviceBean> mDeviceBeans;

    AppActivity mActivity;
    private int actListHeightOffset;

    public BottomDeviceDialog(@NonNull @NotNull Context context) {
        super(context);
    }

    public void setAcitity(AppActivity activity){
        mActivity = activity;
    }
    public void setDeviceBean(DeviceBean deviceBean, Map<String, String> actMap){
        mDevice = deviceBean;
        mActMap.clear();
        if (actMap != null && deviceBean != null){
            for (String key : actMap.keySet()){
                if (deviceBean.getDeviceType().equals(DeviceType.UNIVERSAL_SEQUENCER.stringType) || deviceBean.getDeviceType().equals(DeviceType.UNIVERSAL_PROJECTOR.stringType) || deviceBean.getDeviceType().equals(DeviceType.UNIVERSAL_PLAYER.stringType) || deviceBean.getDeviceType().equals(DeviceType.UNIVERSAL_PA.stringType) || deviceBean.getDeviceType().equals("universal_freshair")){
                    List<UniversalDeviceData> datas = LLDeviceActionDBManager.getInstance(AppApplication.getInstance()).getDeviceDatasByDeviceSerialNo(deviceBean.getDeviceSerialNo());
                    for(UniversalDeviceData data : datas){
                        if(key.equals(data.getActionIdentifier()) && actMap.get(key).equals(data.getRangeIdentifier())){
                            if(mDevice.getDeviceType().equals("universal_sequencer")){
                                mActMap.put(key, new DeviceShotActBean(deviceBean.getType(), deviceBean.getDeviceType(), key, actMap.get(key), deviceBean.getDeviceSerialNo(),String.format("%s:%s",data.getCombineName(),data.getRangeName())));
                            }else{
                                mActMap.put(key, new DeviceShotActBean(deviceBean.getType(), deviceBean.getDeviceType(), key, actMap.get(key), deviceBean.getDeviceSerialNo(),data.getRangeName()));
                            }
                            break;
                        }
                    }
                }else{
                    mActMap.put(key, new DeviceShotActBean(deviceBean.getType(), deviceBean.getDeviceType(), key, actMap.get(key), deviceBean.getDeviceSerialNo()));
                }
            }
        }
        if (isOnCreate){
            updateView();
        }
    }

    public void setIsEdit(Boolean edit){
        isEdit = edit;
    }

    public void setMusicID_dialog(JSONObject jsonObject){
        if (jsonObject==null){
            return;
        }
        deviceView.setMusicID_view(jsonObject);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.device_bottom_dialog;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        deviceImage =  findViewById(R.id.device_image);
        deviceName =  findViewById(R.id.device_name);
        VsetDeviceActs =  findViewById(R.id.device_act_list);
        deviceContentLy =  findViewById(R.id.device_content);
        floorRoomName = findViewById(R.id.floor_room);
        actList =  findViewById(R.id.act_list);
        cancel =  findViewById(R.id.cancel);
        save =  findViewById(R.id.save);
        save.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                onSave(getStatusJson(),mDeviceBeans);
            }
        });
        VsetDeviceActs.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SelectDeviceActivity.class);
                intent.putExtra("type", SelectDeviceActivity.TYPE_SELECT_SAME_DEVICE);
                intent.putExtra("deviceType", mDevice.getDeviceType());
                intent.putExtra("baseDevice", mDevice.getDeviceSerialNo());
                intent.putExtra("showAllSelect", true);
                DataHolder.getInstance().setData("scene_same_device", mDeviceBeans);
                mActivity.startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                    @Override
                    public void onActivityResult(int resultCode,Intent data) {
                        if (resultCode == RESULT_OK) {
                            List<DeviceBean> deviceBeans = (List<DeviceBean>) DataHolder.getInstance().getData("scene_same_device");
//                            List<DeviceBean> deviceBeans = (List<DeviceBean>) intent.getSerializableExtra("deviceList");
                            mDeviceBeans = deviceBeans;
                        }
                    }
                });
//                getContext().startActivity(intent);
//                dismiss();
            }
        });
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        outSide = findViewById(R.id.out_side);
        outSide.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        isOnCreate = true;
        actAdapter = new ActAdapter();
        //new FlowLayoutManager(getContext(), true)
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        actList.setLayoutManager(linearLayoutManager);
        actList.setAdapter(actAdapter);
        actAdapter.addChildClickViewIds(R.id.delete);
        actAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.delete){
                    //更新快照
                    updateShotView(actAdapter.getData().get(position));
                    actAdapter.getData().remove(position);
//                    actAdapter.notifyItemRemoved(position);
                    actAdapter.notifyDataSetChanged();
                    setBtnEnabled();
                }
            }
        });
        VsetDeviceActs.setVisibility(isEdit ? VISIBLE : GONE);
        updateView();
        actListHeightOffset = getResources().getDimensionPixelSize(R.dimen.dp_40);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

    }

    private void updateShotView(DeviceShotActBean actBean){
        mActMap.remove(actBean.name);
        deviceView.setActMap(mActMap);
    }

    private Map<String, String> getStatusJson(){
        if (mActMap == null || mActMap.isEmpty()) return null;
        Map<String, String> value = new LinkedHashMap<>();
        for (String key : mActMap.keySet()){
            value.put(Objects.requireNonNull(mActMap.get(key)).name, Objects.requireNonNull(mActMap.get(key)).value);
        }
         return value;
    }

    private void updateView() {
        GlideApp.with(getContext())
                .load(mDevice.getOnImageUrl())
                //.placeholder(R.drawable.avatar_placeholder_ic)
                //.error(R.drawable.avatar_placeholder_ic)
                .into(deviceImage);
        deviceName.setText(mDevice.getName());
        floorRoomName.setText(LLRoomDBManager.getInstance(getContext()).getFloorRoomName(mDevice.getRoomSerialNo()));
        deviceView = ShotViewManager.getDeviceView(getContext(), mDevice)
                    .setActMap(mActMap)
                    .setChangedListener(this::onActChanged);
        deviceContentLy.removeAllViews();
        deviceContentLy.addView(deviceView);
        actAdapter.setNewInstance(getStatusUi());
        setBtnEnabled();
    }

    private void setBtnEnabled(){
        if(actAdapter.getData() != null && actAdapter.getData().size() > 0){
            save.setEnabled(true);
        }else{
            save.setEnabled(false);
        }
    }
    public void onSave(Map<String, String> statusJson,List<DeviceBean> deviceBeans){};

    @Override
    public void onActChanged(LinkedHashMap<String, DeviceShotActBean> actMap) {
        mActMap = actMap;
        actAdapter.setNewInstance(getStatusUi());
        setBtnEnabled();
    }

    private class ActAdapter extends BaseQuickAdapter<DeviceShotActBean, BaseViewHolder>{

        public ActAdapter() {
            super(0);
        }

        @Override
        protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
            if(viewType == 0){
                return createBaseViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_device_switch_action, parent, false));
            }else{
                return createBaseViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_device_action, parent, false));
            }
        }

        @Override
        protected void convert(BaseViewHolder helper, DeviceShotActBean item) {
            TextView value = helper.getView(R.id.value);
            value.setText(item.uiStr);
        }

        @Override
        public int getItemViewType(int position) {
            DeviceShotActBean item = getData().get(position);
            if(item.type != null && item.type.equals("universal")){
                return 1;
            }
            switch (item.name){
                case POWER:
                    return 0;
                default:
                    return 1;
            }
        }
    }

    public List<DeviceShotActBean> getStatusUi(){
        List<DeviceShotActBean> values = new ArrayList<>();
        for (String key : mActMap.keySet()){
            values.add(mActMap.get(key));
        }
        return values;
    }


    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

    }

    /**
     * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
     *
     * @return
     */
    protected int getPopupWidth() {
        return XPopupUtils.getAppWidth(getContext());
    }

    /**
     * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
     *
     * @return
     */
    protected int getPopupHeight() {
        return XPopupUtils.getAppHeight(getContext());
    }

    @Override
    protected int getMaxWidth() {
        return super.getMaxWidth();
    }
}
